package com.haozi.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haozi.reggie.common.CustomException;
import com.haozi.reggie.dto.SetmealDto;
import com.haozi.reggie.entity.Setmeal;
import com.haozi.reggie.entity.SetmealDish;
import com.haozi.reggie.mapper.SetmealMapper;
import com.haozi.reggie.service.SetmealDishService;
import com.haozi.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐
     * @param setmealDto
     */
    @Transactional
    public void saveWithSetmeal(SetmealDto setmealDto) {
        //增加套餐表数据
        this.save(setmealDto);
        //获取增加后套餐id
        Long setmealId = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
           item.setSetmealId(setmealId);
           return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐
     * @param ids
     */
    @Transactional
    public void deleteWithSetmeal(List<Long> ids) {
        //判断是否有在出售的套餐
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if(count > 0){
            //抛异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        //删除套餐表数据
        this.removeByIds(ids);
        //删除关系表数据 setmeal_dish
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper1);
    }
}
